package edu.bbu.BS.client;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import edu.bbu.BS.client.model.Author;
import edu.bbu.bs.backend.dtos.AuthorDTO;

public class Main {
	static Client client = ClientBuilder.newClient();

	static WebTarget webTarget = client.target("http://rakosi-zenbook:8080/BS-api");
	static WebTarget authorWebTarget = webTarget.path("authors");

	public static List<Author> get() {
		Invocation.Builder invocationBuilder = authorWebTarget.request(MediaType.APPLICATION_JSON);
		Response getResponse = invocationBuilder.get();
		List<AuthorDTO> outputGet = getResponse.readEntity(new GenericType<List<AuthorDTO>>() {
		});

		List<Author> authors = new ArrayList<>();
		for (AuthorDTO author : outputGet) {
			authors.add(AuthorAssembler.DTOToModel(author));
		}

		return authors;
	}

	public static Author post(Author author) {
		Invocation.Builder invocationBuilder = authorWebTarget.request(MediaType.APPLICATION_JSON);
		Response postResponse = invocationBuilder.post(Entity.entity(AuthorAssembler.ModelToDTO(author), MediaType.APPLICATION_JSON));
		AuthorDTO output = postResponse.readEntity(AuthorDTO.class);
		return AuthorAssembler.DTOToModel(output);
	}

	public static void main(String[] args) {
		Author authorToInsert = new Author(5L, "Rakosi", "Alpar");
		System.out.println("Author inserted: " + post(authorToInsert));

		System.out.println();
		for (Author author : get()) {
			System.out.println(author);
		}
	}

}
